<template>
	<view class="content">
		<view class="navbar">
			<up-navbar title="审批配置" :fixed="false" leftIconColor="#fff" :safeAreaInsetTop="true" :autoBack="true">
			</up-navbar>
		</view>


		<!-- 审批配置 -->
		<view class="fd-nav-content" :style="{height: `calc(${scollViewHeight}px)`,top: positionTop +'px'}">
			<section class="dingflow-design">
				<view class="zoom">
					<view :class="'zoom-out'+ (nowVal==50?' disabled':'')" @click="zoomSize(1)"></view>
					<text>{{nowVal}}%</text>
					<view :class="'zoom-in'+ (nowVal==300?' disabled':'')" @click="zoomSize(2)"></view>
				</view>
				<view class="box-scale" id="box-scale" style="overflow: auto;height: 100%;"
					:style="'transform: scale('+nowVal/100+'); transform-origin: 50% 0px 0px;'">

					<m-node-warp v-model:nodeConfig.sync="nodeConfig" v-model:flowPermission.sync="flowPermission"
						:isTried.sync="isTried" :directorMaxLevel="directorMaxLevel" :tableId="tableId"></m-node-warp>
					<view class="end-node">
						<view class="end-node-circle"></view>
						<view class="end-node-text">流程结束</view>
					</view>
				</view>
			</section>
		</view>


		<view class="x-f BottomBox" :style="{'padding-bottom':safeAreaBottom+'px','height': btnHeight + 'px'}">

			<uni-popup ref="showFlowChart" mode="center" :mask-click="false" border-radius="10px 10px 10px 10px">
				<view class="f-dc" style="width: 90vw;max-height: 80vh;min-height: 40vh;background-color: #fff;">
					<u-cell title="发起审批" style="background-color: #51d0d0;"
						:titleStyle="{color: '#fff',fontSize: '12px'}">
						<template slot="right-icon">
							<view @click="closeFlowChart">
								<u-icon name="close" color="#fff" size="16"></u-icon>
							</view>
						</template>
					</u-cell>

					<!-- <view style="flex: 1;overflow: auto;background-color: #fffbea;"> -->
					<mFlowCharts ref="flowCharts" style="flex: 1;overflow: auto;" :option="flowChartData">
					</mFlowCharts>
					<!-- </view> -->

					<view class="x-ec" style="width: 100%;height: 40px;">
						<button class="content_bottom_primary_plainBtn CommonBtnSize" @click="closeFlowChart"
							style="padding: 6px 15px !important;margin-right: 8px;">取消</button>
						<button class="content_bottom_primary_Btn CommonBtnSize" @click="submitFlowChart"
							style="padding: 6px 15px !important;margin-right: 8px;">确定</button>
					</view>

				</view>
			</uni-popup>


			<view class="BottomBox-btnBox">
				<button @click="cancelConfigBtn" class="content_bottom_primary_plainBtn CommonBtnSize">取消</button>
				<button @click="submitConfigBtn" class="content_bottom_primary_Btn CommonBtnSize">确定</button>
			</view>
		</view>


	</view>
</template>

<script>
	import mFlowCharts from '@/uni_modules/mc-ui/components/m-node-warp/components/m-flow-charts/m-flow-charts.vue';

	import {
		useMainStore,
		useInventoryStore,
		useUserStore
	} from '@/store';

	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	export default {
		components: {
			mFlowCharts
		},
		data() {
			return {
				positionTop: 44,
				scollViewHeight: 300,
				btnHeight: 60,
				safeAreaBottom: 0,
				isTried: false,
				tipList: [],
				tipVisible: false,
				nowVal: 100,
				BaseScreenParm: {},
				globalData: {},
				processConfig: {},
				nodeConfig: {},
				workFlowDef: {},
				flowPermission: [],
				directorMaxLevel: 0,
				dialogVisible: true,
				tableId: "",

				source: '',

				flowChartData: {},
				eventChannel: null,
			};
		},
		computed: {
			inventoryStore() {
				return useInventoryStore();
			},
			mainStore() {
				return useMainStore();
			},
			userStore() {
				return useUserStore();
			},
			Request() {
				return useRequestQueue();
			}
		},
		watch: {
			nodeConfig: {
				handler(nVal, oVal) {
					console.log(nVal);
					// uni.$utils.addZIndex(this.processConfig.nodeConfig)
					uni.$utils.addZIndex(this.processConfig.nodeConfig);
					this.nodeConfig = this.processConfig.nodeConfig;
					this.flowPermission = this.processConfig.flowPermission;
					this.directorMaxLevel = this.processConfig.directorMaxLevel;
					this.workFlowDef = this.processConfig.workFlowDef;
					this.tableId = this.processConfig.tableId;
					this.inventoryStore.st_comPageConfig.nodeConfig = this.nodeConfig;

				},
				deep: true
			}
		},
		onLoad(option) {
			this.eventChannel = this.getOpenerEventChannel();



			let BaseScreenParm = uni.$utils.deepClone(this.mainStore.BaseScreenParm);
			console.log(BaseScreenParm);

			this.BaseScreenParm = BaseScreenParm;
			this.processConfig = BaseScreenParm.approveObj;
			this.globalData = BaseScreenParm.globalData;

			// uni.$utils.addZIndex(this.processConfig.nodeConfig);
			uni.$utils.addZIndex(this.processConfig.nodeConfig);
			this.nodeConfig = this.processConfig.nodeConfig;
			this.nodeConfig = this.processConfig.nodeConfig;
			this.flowPermission = this.processConfig.flowPermission;
			this.directorMaxLevel = this.processConfig.directorMaxLevel;
			this.workFlowDef = this.processConfig.workFlowDef
			this.tableId = this.processConfig.tableId

			this.source = option.source
		},
		mounted() {
			let that = this;
			setTimeout(() => {
				that.getViewHeight();
			}, 300);
		},
		onUnload() {
			this.eventChannel.emit('cancel');
			uni.$off('gitCellCardInfo' + this.inventoryStore.st_comPageConfig.nodewarpIndex);

			this.inventoryStore.st_comPageConfig.nodeConfig = {};
		},
		methods: {
			getViewHeight() { // 获取高度
				let that = this;
				let res = uni.getSystemInfoSync();

				let safeArea = res.safeAreaInsets; // 安全区域嵌入 top - bottom
				let safe = safeArea.top + safeArea.bottom
				// let windowHeight = res.windowHeight - safe; // 总高
				let windowHeight = res.windowHeight; // 总高
				let navHeight = 0;
				setTimeout(() => {
					uni.createSelectorQuery().select('.navbar').boundingClientRect(rect => {
						navHeight = rect.height;
						// let positionTop = navHeight + safeArea.top;
						that.positionTop = navHeight;


						uni.createSelectorQuery().select('.BottomBox').boundingClientRect(ret => {
							if (uni.getStorageSync('safeAreaBottom')) {
								that.safeAreaBottom = (+uni.getStorageSync('safeAreaBottom')) / 2;
							}

							let btnHeight = +ret.height + +that.safeAreaBottom;
							that.btnHeight = btnHeight;
							let nextData = windowHeight - (+navHeight + btnHeight);
							that.scollViewHeight = nextData;
						}).exec();


						// let nextData = windowHeight - (+navHeight + 60 + +safeArea.bottom);
						// console.log(nextData);

					}).exec();
				}, 300);
			},

			toReturn() {
				//window.location.href = ""
			},
			reErr(data) {
				if (data.childNode) {
					if (data.childNode.type == 1) { //审批人
						if (data.childNode.error) {
							this.tipList.push({
								name: data.childNode.nodeName,
								type: "审核人"
							})
						}
						this.reErr(data.childNode)
					} else if (data.childNode.type == 2) {
						if (data.childNode.error) {
							this.tipList.push({
								name: data.childNode.nodeName,
								type: "抄送人"
							})
						}
						this.reErr(data.childNode)
					} else if (data.childNode.type == 3) {
						this.reErr(data.childNode.childNode)
					} else if (data.childNode.type == 4) {
						this.reErr(data.childNode)
						for (let i = 0; i < data.childNode.conditionNodes.length; i++) {
							if (data.childNode.conditionNodes[i].error) {
								this.tipList.push({
									name: data.childNode.conditionNodes[i].nodeName,
									type: "条件"
								})
							}
							this.reErr(data.childNode.conditionNodes[i])
						}
					}
				} else {
					data.childNode = null
				}
			},
			saveSet() {
				this.isTried = true;
				this.tipList = [];
				this.reErr(this.nodeConfig);
				if (this.tipList.length != 0) {
					this.tipVisible = true;
					return;
				}
				this.processConfig.flowPermission = this.flowPermission;

			},
			zoomSize(type) {
				debugger;
				if (type == 1) {
					if (this.nowVal == 50) {
						return;
					}
					this.nowVal -= 10;
				} else {
					if (this.nowVal == 300) {
						return;
					}
					this.nowVal += 10;
				}
			},
			submitConfigBtn() { // 确认按钮

				this.flowChartData = uni.$utils.deepClone(this.processConfig);

				// 展示流程
				this.$refs['showFlowChart'].open()
			},
			cancelConfigBtn() { // 取消按钮
				uni.navigateBack();
			},
			submitFlowChart() { // 流程弹层确认按钮
				let that = this;
				uni.$utils.showLoading();
				console.log(that.processConfig);
				let mainSql = ''
				let obj = {}
				if (that.source == 'QMS') {
					//插入主表信息
					mainSql =
						" insert into SYS_BillAPFlow(Type,BillName,APType,CreateTime,AppConfigStr,FormID) values('999',@BillName,1,getdate(),@AppConfigStr,@FormID) select @@identity as APFlowID ";

					obj = {
						BillName: that.processConfig.workFlowDef.name,
						AppConfigStr: JSON.stringify(that.processConfig),
						FormID: that.globalData.Id
					};
				} else {
					//插入主表信息
					mainSql =
						" insert into SYS_BillAPFlow(Type,BillName,APType,CreateTime,AppConfigStr,APPFormID) values('999',@BillName,1,getdate(),@AppConfigStr,@APPFormID) select @@identity as APFlowID ";

					obj = {
						BillName: that.processConfig.workFlowDef.name,
						AppConfigStr: JSON.stringify(that.processConfig),
						APPFormID: that.globalData.Id
					};
				}
				/*
				//插入主表信息
				let mainSql =
					" insert into SYS_BillAPFlow(Type,BillName,APType,CreateTime,AppConfigStr,APPFormID) values('999',@BillName,1,getdate(),@AppConfigStr,@APPFormID) select @@identity as APFlowID ";
				
				let obj = {
					BillName: that.processConfig.workFlowDef.name,
					AppConfigStr: JSON.stringify(that.processConfig),
					APPFormID: that.globalData.Id
				};
				*/
				try {
					console.log(obj);
					that.post(mainSql, obj, function(retFlow) {
						console.log(retFlow);
						let APFlowID = retFlow.ds[0].APFlowID;
						let appConfigObj = uni.$utils.deepClone(that.processConfig);
						let aPUserIDs = [],
							classIDs = [];
						for (let q = 0; q < appConfigObj.flowPermission.length; q++) {
							if (appConfigObj.flowPermission[q].type == 1) {
								aPUserIDs.push(appConfigObj.flowPermission[q].targetId);
							} else if (appConfigObj.flowPermission[q].type == 3) {
								classIDs.push(appConfigObj.flowPermission[q].targetId);
							}
						};


						//保存发起人
						let sql =
							'insert into SYS_BillAPFlowDe(APFlowID,APFlowNO,APUserID,RoleIDs,JobLevel,ClassIDs,SignedWay,FlowType) values(@APFlowID,@APFlowNO,@APUserID,@RoleIDs,@JobLevel,@ClassIDs,@SignedWay,@FlowType)';
						that.post(sql, {
							APFlowID: APFlowID,
							APFlowNO: '0',
							APUserID: aPUserIDs.join(','),
							RoleIDs: '',
							JobLevel: '0',
							ClassIDs: classIDs.join(','),
							SignedWay: '0',
							FlowType: '0'
						}, function() {});


						//保存各级审批及抄送人
						let saveApproveFunc = function(node, flowNo) {
							let caPUserIDs = [],
								cclassIDs = [],
								croleIDs = []
							let Joblevel = 0;
							let flowType = 0;
							let signedWay = 0;
							for (let k = 0; k < node.nodeUserList.length; k++) {
								if (node.nodeUserList[k].type == 1) {
									caPUserIDs.push(node.nodeUserList[k].targetId);
								} else if (node.nodeUserList[k].type == 3) {
									cclassIDs.push(node.nodeUserList[k].targetId);
								} else if (node.nodeUserList[k].type == 2) {
									croleIDs.push(node.nodeUserList[k].targetId);
								}
							}
							if (node.settype == 7) {
								Joblevel = node.examineEndDirectorLevel;
							}
							if (node.type == 1) {
								flowType = 0;
							} else {
								flowType = 1;
							}
							if (node.examineMode == 1) {
								signedWay = 0;
							} else {
								signedWay = 1;
							}

							that.post(sql, {
								APFlowID: APFlowID,
								APFlowNO: flowNo,
								APUserID: caPUserIDs.join(','),
								RoleIDs: croleIDs.join(','),
								JobLevel: Joblevel,
								ClassIDs: cclassIDs.join(','),
								SignedWay: signedWay,
								FlowType: flowType
							}, function() {});
							flowNo++;
							if (node.childNode) {
								saveApproveFunc(node.childNode, flowNo);
							}
						};

						saveApproveFunc(appConfigObj.nodeConfig.childNode, 1);

						setTimeout(() => {
							that.Request.requestByUrl({
								config: {
									baseURL: "/Approve/BgApproval"
								},
								url: '',
								method: 'POST',
								data: {
									approveType: 0,
									tableName: that.globalData.physicalTableName,
									keyName: that.BaseScreenParm.keyName,
									keyId: that.BaseScreenParm.keyValue,
									APFlowID: APFlowID,
									userId: that.userStore.UserInfo.UserID,
									title: that.processConfig.workFlowDef.name,
								},
								success(approveRet) {
									uni.$utils.showLoading();

									if (approveRet.data.ds[0].status == "500") {
										uni.$utils.msg(approveRet.data.ds[0].msg)
									} else {
										uni.navigateBack({
											delta: 1,
											success() {
												that.eventChannel.emit('doneConfirm', 0);
											}
										})
									}
								}
							});


						}, 1000)

					})


				} catch (e) {
					uni.$utils.showLoading();
					//TODO handle the exception
				}

			},
			closeFlowChart() { // 流程弹层取消按钮
				this.$refs.showFlowChart.close();
			},
			post(sql, param, callBack) {
				console.log(sql);
				console.log(param);
				param["sql"] = sql;
				let UserInfo = this.userStore.UserInfo;
				if (UserInfo) {
					if (!param.hasOwnProperty("P_UserID")) {
						param.P_UserID = UserInfo.UserID;
					}
					if (!param.hasOwnProperty("P_UserName")) {
						param.P_UserName = UserInfo.UserName;
					}
					if (!param.hasOwnProperty("P_UserCode")) {
						param.P_UserCode = UserInfo.UserCode;
					}
				}
				console.log(param);
				debugger
				try {
					this.Request.requestByUrl({
						config: {
							baseURL: "/SQLData/QuerySql"
						},
						url: '',
						method: 'POST',
						data: param,
						success(ret) {
							console.log(ret);
							callBack(ret);
						},
						fail(err) {
							console.log(err);
						}
					});
				} catch (error) {
					console.log(error);
				}

			},
		}
	}
</script>

<style lang="scss" scoped>
	@import "/static/assets/css/nodeWarp/workflow.css";


	/* #ifdef MP-WEIXIN */
	view {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	/* #endif */

	/* #ifndef MP-WEIXIN */
	* {
		margin: 0;
		padding: 0;
		box-sizing: border-box;
	}

	/* #endif */



	.error-modal-list {
		width: 455px;
	}

	.BottomBox {
		z-index: 9;
		position: fixed;
		bottom: 0;
		left: 0;
		height: 60px;
		width: 100vw;
		background-color: #fff;

		&-btnBox {
			height: 100%;
			width: 100%;
			display: flex;
			align-items: center;
			justify-content: flex-end;

			.CommonBtnSize {
				padding: 10px 15px !important;
				margin-right: 8px;
			}
		}
	}
</style>